﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Xml;
using System.Text.RegularExpressions;

namespace Util.IO
{
    public class FileUtil
    {
        public static void EnsureDir(DirectoryInfo dir)
        {
            if (dir == null)
            {
                throw new ArgumentNullException("dir");
            }
            if (!dir.Exists)
            {
                dir.Create();
            }
        }

        public static void EnsureDir(FileInfo file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            EnsureDir(file.Directory);
        }


        public static void EnsureDir(string dirPath)
        {
            if (string.IsNullOrWhiteSpace(dirPath))
            {
                throw new ArgumentException("空指针或空串", "dirPath");
            }
            EnsureDir(new DirectoryInfo(dirPath));
        }
        public static bool CopyFile(FileInfo src, FileInfo target, bool isCover)
        {
            if (target.Exists)
            {
                if (isCover == false)
                {
                    return false;
                }
                target.Delete();
            }
            return src.CopyTo(target.FullName) != null ? true : false;
        }

        public static IEnumerable<FileInfo> ListFiles(DirectoryInfo dir, FileFilter filter, bool isCached = true)
        {
            IEnumerable<string> paths;
            string cachedHtmlFileName = CachedHtmlFileName(dir);
            Regex regex = (filter.FileNameRegex == null ? null : new Regex(filter.FileNameRegex, RegexOptions.Compiled));
            if (!isCached || !File.Exists(cachedHtmlFileName))
            {
                IEnumerable<FileInfo> files = dir.EnumerateFiles(filter.FileExtension == null ? "*" : "*." + filter.FileExtension, filter.SearchOption);
                files = regex == null ? files : files.Where(t => regex.IsMatch(t.FullName));
                if (isCached)
                {
                    paths = files.Select(t => t.FullName);
                    File.WriteAllLines(cachedHtmlFileName, paths);
                }
                return files;
            }
            paths = File.ReadAllLines(cachedHtmlFileName);
            return regex == null ? paths.Select(t => new FileInfo(t)) : paths.Where(t => regex.IsMatch(t)).Select(t => new FileInfo(t));
        }

        static private string CachedHtmlFileName(DirectoryInfo dir)
        {
            return dir.Parent.FullName + "\\" + dir.Name + ".files.txt";
        }

        public static  void OpenJobDir()
        {
            string path = "jobs\\output";
            DirectoryInfo dir = new DirectoryInfo(path);
            if (!dir.Exists)
            {
                dir.Create();
            }
            System.Diagnostics.Process.Start("explorer.exe", path);
        }
    }
}
